package common.util.generate.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import common.core.util.CommonUtil;
import common.core.util.CustomizeRuntimeException;
import common.util.generate.dao.JdbcDao;
import common.util.generate.properties.*;
import common.util.generate.service.GenerateService;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.*;
import java.util.*;

/**
 * @author liubo
 * @created 2020-06-29 10:32
 */
@Slf4j
@Service
public class GenerateServiceImpl implements GenerateService {

    @Autowired
    private GenerateProperties generateProperties;

    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Autowired
    private JdbcDao jdbcDao;

    private ParamProperties param = new ParamProperties();
    private Configuration configuration=new Configuration(Configuration.VERSION_2_3_22);;
    private InfoProperties infoProperties = new InfoProperties();

    @Override
    public void generateFile() throws Exception {
        // 初始化 param;
        this.initParamProterties();
        //初始化配置信息
        this.initConfiguration();
        //初始化文件创建信息
        this.initCreate();
        // 生成 help.java 文件
        this.generateHelpFile();
        // 生成entity.java 文件
        this.generateEntityFile();
        // 生成param.java 文件
        this.generateParamFile();
        // 生成vo.java 文件
        this.generateVoFile();
        // 生成queryForOneRowParam.java 文件
        this.generateQueryForOneRowParamFile();
        // 生成queryPageParam.java 文件
        this.generateQueryPageParamFile();
        // 生成Mapper.java 文件
        this.generateMapperFile();
        // 生成Mapper.xml 文件
        this.generateXmlFile();
        // 生成service.java 文件
        this.generateServiceFile();
        // 生成serviceImpl.java 文件
        this.generateServiceImplFile();
        // 生成controller.java 文件
        this.generateControllerFile();
        // 生成feign.java 文件
        /*this.generateFeignFile();
        // 生成feign.java 文件
        this.generateFeignFallbackFile();*/
    }

    private void initCreate() {
        InfoProperties info = generateProperties.getInfo();
        Map<String,Object> map = JSONObject.parseObject(JSONObject.toJSONString(info, SerializerFeature.WriteMapNullValue),Map.class);
        Boolean isAllNull = true;
        Boolean containsTrue = false;
        for (String key : map.keySet()) {
            if(key.toLowerCase().endsWith("generate")) {
                if (null != map.get(key)) {
                    isAllNull = false;
                    if ((Boolean) map.get(key)) {
                        containsTrue = true;
                    }
                }
            }
        }
        if(isAllNull){
            for (String key : map.keySet()) {
                if(key.toLowerCase().endsWith("generate")) {
                    map.put(key,true);
                }
            }
        }
        if(containsTrue){
            for (String key : map.keySet()) {
                if(key.toLowerCase().endsWith("generate")) {
                    if(null == map.get(key)){
                        map.put(key,false);
                    }
                }
            }
        }
        for (String key : map.keySet()) {
            if(key.toLowerCase().endsWith("generate")) {
                String priKey = key.substring(0 ,key.length()-"generate".length())+"PackagePath";
                if( null == map.get(priKey)){
                    log.info("{} 为空,文件不生成",priKey);
                    map.put(key,false);
                }
            }
        }
        this.infoProperties = JSONObject.parseObject(JSONUtils.toJSONString(map),InfoProperties.class) ;
    }
    /*void generateFeignFile() throws Exception {
        if(!infoProperties.getFeignGenerate()){
            log.info("跳过--{}文件生成","Feign");
            return;
        }
        log.info("开始--{}文件生成","Feign");
        InfoProperties info =  generateProperties.getInfo();
        String path = info.getFeignAbsoluteSavePath()==null? info.getAbsoluteSavePath():info.getFeignAbsoluteSavePath();
        path = getJavaFilePath( info, path,  info.getFeignPackagePath());

        this.generateFileByTemplate(generateProperties.getFtl().getFeignPath(), new File(path));
        log.info("完成--{}文件生成","Feign");
    }

    void generateFeignFallbackFile() throws Exception {
        if(!infoProperties.getFeignFallbackGenerate()){
            log.info("跳过--{}文件生成","FeignFallback");
            return;
        }
        log.info("开始--{}文件生成","FeignFallback");
        InfoProperties info =  generateProperties.getInfo();
        String path = info.getFeignFallbackAbsoluteSavePath()==null? info.getAbsoluteSavePath():info.getFeignFallbackAbsoluteSavePath();
        path = getJavaFilePath( info, path,  info.getFeignFallbackPackagePath());

        this.generateFileByTemplate(generateProperties.getFtl().getFeignFallbackPath(), new File(path));
        log.info("完成--{}文件生成","FeignFallback");
    }*/

    void generateControllerFile() throws Exception {
        if(!infoProperties.getControllerGenerate()){
            log.info("跳过--{}文件生成","controller");
            return;
        }
        log.info("开始--{}文件生成","controller");
        InfoProperties info =  generateProperties.getInfo();
        String path = info.getControllerAbsoluteSavePath()==null? info.getAbsoluteSavePath():info.getControllerAbsoluteSavePath();
        path = getJavaFilePath( info, path,  info.getControllerPackagePath());

        this.generateFileByTemplate(generateProperties.getFtl().getControllerPath(), new File(path));
        log.info("完成--{}文件生成","controller");
    }

    void generateServiceImplFile() throws Exception {
        if(!infoProperties.getServiceImplGenerate()){
            log.info("跳过--{}文件生成","serviceImpl");
            return;
        }
        log.info("开始--{}文件生成","serviceImpl");
        InfoProperties info =  generateProperties.getInfo();
        String path = info.getServiceImpAbsolutelSavePath()==null? info.getAbsoluteSavePath():info.getServiceImpAbsolutelSavePath();
        path = getJavaFilePath( info, path, info.getServiceImplPackagePath());

        this.generateFileByTemplate(generateProperties.getFtl().getServiceImplPath(), new File(path));
        log.info("完成--{}文件生成","serviceImpl");
    }
    void generateServiceFile() throws Exception {
        if(!infoProperties.getServiceGenerate()){
            log.info("跳过--{}文件生成","service");
            return;
        }
        log.info("开始--{}文件生成","service");
        InfoProperties entity =  generateProperties.getInfo();
        String path = entity.getServiceAbsoluteSavePath()==null? entity.getAbsoluteSavePath():entity.getServiceAbsoluteSavePath();
        path = getJavaFilePath( entity, path, entity.getServicePackagePath());

        this.generateFileByTemplate(generateProperties.getFtl().getServicePath(), new File(path));
        log.info("完成--{}文件生成","service");
    }
    void generateXmlFile() throws Exception {
        if(!infoProperties.getXmlGenerate()){
            log.info("跳过--{}文件生成","xml");
            return;
        }
        log.info("开始--{}文件生成","xml");
        InfoProperties entity =  generateProperties.getInfo();
        String path = entity.getXmlAbsoluteSavePath()==null? entity.getAbsoluteSavePath():entity.getXmlAbsoluteSavePath();

        String filePath = entity.getXmlPackagePath().replaceAll("&entity&", param.getTable().getEntityName());

        String prefix = filePath.substring(0, 10);
        if("resources:".equalsIgnoreCase(prefix)){
            filePath = filePath.split(":")[1];
            path = path +"/src/main/resources/";
        }else if("classpath:".equalsIgnoreCase(prefix)){
            filePath = generateProperties.getInfo().getBaseSavePackagePath() + "/"  + filePath.split(":")[1];
            path = path +"/src/main/java/";
        }else{
            path = path +"/src/main/resources/";
        }

        path = path.replaceAll("\\\\", "/");
        String packagePath = filePath;
        packagePath = packagePath.replaceAll("\\.", "/");
        packagePath = packagePath.substring(0,packagePath.lastIndexOf("/xml"))+".xml";
        path = path +packagePath;

        this.generateFileByTemplate(generateProperties.getFtl().getXmlPath(), new File(path));
        log.info("完成--{}文件生成","xml");
    }

    void generateMapperFile() throws Exception {
        if(!infoProperties.getMapperGenerate()){
            log.info("跳过--{}文件生成","mapper");
            return;
        }
        log.info("开始--{}文件生成","mapper");
        InfoProperties entity =  generateProperties.getInfo();
        String path = entity.getMapperAbsoluteSavePath()==null? entity.getAbsoluteSavePath():entity.getMapperAbsoluteSavePath();
        path = getJavaFilePath(entity, path, entity.getMapperPackagePath());

        this.generateFileByTemplate( generateProperties.getFtl().getMapperPath(), new File(path));
        log.info("完成--{}文件生成","mapper");
    }

    private String getJavaFilePath( InfoProperties info, String path, String mapperPackagePath) {
        String filePath = mapperPackagePath.replaceAll("&entity&", param.getTable().getEntityName());
        path = path + "/src/main/java/";
        path = path.replaceAll("\\\\", "/");
        String packagePath = info.getBaseSavePackagePath() + "/"  + filePath;
        packagePath = packagePath.replaceAll("\\.", "/");
        packagePath = packagePath.substring(0,packagePath.lastIndexOf("/java"))+".java";
        path = path + packagePath;
        return path;
    }

    void generateEntityFile() throws Exception {
        if(!infoProperties.getEntityGenerate()){
            log.info("跳过--{}文件生成","entity");
            return;
        }
        log.info("开始--{}文件生成","entity");
        InfoProperties entity =  generateProperties.getInfo();
        String path = entity.getEntityAbsoluteSavePath()==null? entity.getAbsoluteSavePath():entity.getEntityAbsoluteSavePath();
        path = getJavaFilePath(entity, path, entity.getEntityPackagePath());

        this.generateFileByTemplate( generateProperties.getFtl().getEntityPath(), new File(path));
        log.info("完成--{}文件生成","entity");
    }
    void generateVoFile() throws Exception {
        if(!infoProperties.getVoGenerate()){
            log.info("跳过--{}文件生成","vo");
            return;
        }
        log.info("开始--{}文件生成","vo");
        InfoProperties entity =  generateProperties.getInfo();
        String path = entity.getVoAbsoluteSavePath()==null? entity.getAbsoluteSavePath():entity.getVoAbsoluteSavePath();
        path = getJavaFilePath(entity, path, entity.getVoPackagePath());

        this.generateFileByTemplate( generateProperties.getFtl().getVoPath(), new File(path));
        log.info("完成--{}文件生成","vo");
    }
    void generateQueryPageParamFile() throws Exception {
        if(!infoProperties.getQueryPageParamGenerate()){
            log.info("跳过--{}文件生成","queryPageParam");
            return;
        }
        log.info("开始--{}文件生成","queryPageParam");
        InfoProperties entity =  generateProperties.getInfo();
        String path = entity.getQueryPageParamAbsoluteSavePath()==null? entity.getAbsoluteSavePath():entity.getQueryPageParamAbsoluteSavePath();
        path = getJavaFilePath(entity, path, entity.getQueryPageParamPackagePath());

        this.generateFileByTemplate( generateProperties.getFtl().getQueryPageParamPath(), new File(path));
        log.info("完成--{}文件生成","queryPageParam");
    }

    void generateQueryForOneRowParamFile() throws Exception {
        if(!infoProperties.getQueryForOneRowParamGenerate()){
            log.info("跳过--{}文件生成","queryForOneRowParam");
            return;
        }
        log.info("开始--{}文件生成","queryForOneRowParam");
        InfoProperties entity =  generateProperties.getInfo();
        String path = entity.getQueryForOneRowParamAbsoluteSavePath()==null? entity.getAbsoluteSavePath():entity.getQueryForOneRowParamAbsoluteSavePath();
        path = getJavaFilePath(entity, path, entity.getQueryForOneRowParamPackagePath());

        this.generateFileByTemplate( generateProperties.getFtl().getQueryForOneRowParamPath(), new File(path));
        log.info("完成--{}文件生成","queryForOneRowParam");
    }

    void generateParamFile() throws Exception {
        if(!infoProperties.getParamGenerate()){
            log.info("跳过--{}文件生成","param");
            return;
        }
        log.info("开始--{}文件生成","param");
        InfoProperties entity =  generateProperties.getInfo();
        String path = entity.getParamAbsoluteSavePath()==null? entity.getAbsoluteSavePath():entity.getParamAbsoluteSavePath();
        path = getJavaFilePath(entity, path, entity.getParamPackagePath());

        this.generateFileByTemplate( generateProperties.getFtl().getParamPath(), new File(path));
        log.info("完成--{}文件生成","param");
    }
    void generateHelpFile() throws Exception {
        if(!infoProperties.getHelpGenerate()){
            log.info("跳过--{}文件生成","help");
            return;
        }
        log.info("开始--{}文件生成","help");
        InfoProperties entity =  generateProperties.getInfo();
        String path = entity.getHelpAbsoluteSavePath()==null? entity.getAbsoluteSavePath():entity.getHelpAbsoluteSavePath();
        path = getJavaFilePath( entity, path, entity.getHelpPackagePath());
        File file = new File(path);
        if(file.exists()){
            path=path+".bak";
            log.info("开始--{}文件存在生成.bak文件","help");
        }
        this.generateFileByTemplate( generateProperties.getFtl().getHelpPath(), new File(path));
        log.info("完成--{}文件生成","help");
    }




    private void generateFileByTemplate( final String templateName,File file) throws Exception {
        File packageFile = new File(file.getParent());
        if(!packageFile.exists()){
            packageFile.mkdirs();
        }
        Template template = configuration.getTemplate(templateName);
        FileOutputStream fos = new FileOutputStream(file);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"),10240);
        template.process(param,out);
    }
    /**
     * 初始化freemarker 配置
     * @return
     */
    private Configuration initConfiguration() {
        configuration.setTemplateLoader(new ClassTemplateLoader(FreeMarkerTemplateUtils.class, "/templates"
                +(StringUtils.isBlank(generateProperties.getFtl().getModel())?"":("/"+generateProperties.getFtl().getModel()))));
        configuration.setDefaultEncoding("UTF-8");
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        configuration.setCacheStorage(NullCacheStorage.INSTANCE);
        return configuration;
    }
    private void initParamProterties(){
        InfoProperties info = generateProperties.getInfo();
        param.setAuthor(generateProperties.getAuthor());
        param.setBaseSavePackagePath(info.getBaseSavePackagePath());
        TableProperties table = this.getTableProperties();
        List<TableFieldProperties> fields = this.getTableFieldProperties();
        table.setFields(fields);
        List<String> pks = this.getPrimaryKeys();
        Set<String> pkSet = new HashSet<>();
        for (String pk : pks) {
            pkSet.add(pk.toLowerCase());
        }

        Set<String> commonSet =  new HashSet<>();
        for (String cs:info.getCommonFields().split(",")){
            commonSet.add(cs.toLowerCase());
        }

        for(TableFieldProperties field : table.getFields()){
            if( pkSet.contains(field.getFieldName().toLowerCase())){
                field.setPkField(true);
            }else {
                field.setPkField(false);
            }
            if(commonSet.contains(field.getFieldName().toLowerCase())){
                field.setCommonField(true);
            }else {
                field.setCommonField(false);
            }
        }

        String entityName = info.getEntityTableName().toLowerCase()
                .replace(info.getPrefix().toLowerCase(),"");
        entityName =this.dbForDBToHump(entityName.startsWith("_")?(entityName.substring(1, entityName.length())):entityName);

        PackageProperties pk = param.getPk();
        table.setEntityName(entityName);
        param.setModel(generateProperties.getInfo().getModel());
        param.setTableName(generateProperties.getInfo().getEntityTableName());
        param.setTable(table);
        log.info("初始化 {} 完成",TableProperties.class.getName());


        String commonPackage = info.getBaseSavePackagePath();
        String model = info.getModel();
        if(StringUtils.isBlank(commonPackage)
                ||StringUtils.isBlank(model)){
            log.error("设置了absoluteSavePath属性后必须设置model,baseSavePackagePath属性");
        }

        // help
        String helpPath = info.getHelpPackagePath();
        if(StringUtils.isBlank(helpPath)){
            log.error("没有设置help文件的 helpPackagePath 会导致Help文件生成失败");
        } else {
            List<String> helpList = getStrings(entityName, commonPackage,  helpPath);
            pk.setHelpName(this.getFileNameBylist(helpList));
            pk.setHelpPackage(this.getPackageByList(helpList));
            pk.setHelpSuperClassNme(this.getFileNameBySuperPath(info.getHelpSuperClassName()));
            pk.setHelpSuperClassPackage(this.getPackageBySuperPath(info.getHelpSuperClassName()));
        }

        //entity
        String entityPath = info.getEntityPackagePath();
        if(StringUtils.isBlank(entityPath)){
            log.error("没有设置entity文件的 entityPackagePath会导致 会导致entity文件生成失败");
        }else {
            List<String> entityList = getStrings(entityName, commonPackage, entityPath);
            pk.setEntityName(this.getFileNameBylist(entityList));
            pk.setEntityPackage(this.getPackageByList(entityList));
            pk.setEntitySuperClassName(this.getFileNameBySuperPath(info.getEntitySuperClassName()));
            pk.setEntitySuperClassPackage(this.getPackageBySuperPath(info.getEntitySuperClassName()));
        }

        //param
        String paramPath = info.getParamPackagePath();
        if(StringUtils.isBlank(paramPath)){
            log.error("没有设置param文件的 paramPackagePath会导致 会导致param文件生成失败");
        }else {
            List<String> paramList = getStrings(entityName, commonPackage, paramPath);
            pk.setParamName(this.getFileNameBylist(paramList));
            pk.setParamPackage(this.getPackageByList(paramList));
        }
        //vo
        String voPath = info.getVoPackagePath();
        if(StringUtils.isBlank(voPath)){
            log.error("没有设置vo 文件的 voPath会导致 会导致vo文件生成失败");
        }else {
            List<String> voList = getStrings(entityName, commonPackage, voPath);
            pk.setVoName(this.getFileNameBylist(voList));
            pk.setVoPackage(this.getPackageByList(voList));
        }

        //queryPagevo
        String queryPageParamPath = info.getQueryPageParamPackagePath();
        if(StringUtils.isBlank(queryPageParamPath)){
            log.error("没有设置queryPageParam 文件的 queryPageParamPath 会导致queryPageParam文件生成失败");
        }else {
            List<String> voList = getStrings(entityName, commonPackage, queryPageParamPath);
            pk.setQueryPageParamName(this.getFileNameBylist(voList));
            pk.setQueryPageParamPackage(this.getPackageByList(voList));
        }
        //queryForOneRowParam
        String queryForOneRowParamPath = info.getQueryForOneRowParamPackagePath();
        if(StringUtils.isBlank(queryForOneRowParamPath)){
            log.error("没有设置queryForOneRowParam 文件的 queryForOneRowParamPath会导致 会导致queryForOneRowParam文件生成失败");
        }else {
            List<String> queryForOneRowParam = getStrings(entityName, commonPackage, queryForOneRowParamPath);
            pk.setQueryForOneRowParamName(this.getFileNameBylist(queryForOneRowParam));
            pk.setQueryForOneRowParamPackage(this.getPackageByList(queryForOneRowParam));
        }


        //xml
        String xmlPath = info.getXmlPackagePath();
        if(StringUtils.isBlank(xmlPath)){
            log.error("没有设置xml文件的 xmlPackagePath 会导致xml文件生成失败");
        }else{
            List<String> xmlList = getStrings(entityName, "",  xmlPath);
            pk.setXmlName(this.getFileNameBylist(xmlList));
            pk.setXmlPackage(this.getPackageByList(xmlList));
        }
        //service
        String servicePath = info.getServicePackagePath();
        if(StringUtils.isBlank(servicePath)){
            log.error("没有设置service文件的 servicePackagePath会导致 会导致service文件生成失败");
        }else {
            List<String> serviceList = getStrings(entityName, commonPackage, servicePath);
            pk.setServiceName(this.getFileNameBylist(serviceList));
            pk.setServicePackage(this.getPackageByList(serviceList));
            pk.setServiceSuperClassNme(this.getFileNameBySuperPath(info.getServiceSuperClassName()));
            pk.setServiceSuperClassPackage(this.getPackageBySuperPath(info.getServiceSuperClassName()));
        }
        //serviceImpl
        String serviceImplPath = info.getServiceImplPackagePath();
        if(StringUtils.isBlank(serviceImplPath)){
            log.error("没有设置serviceImpl文件的 serviceImplPackagePath会导致 会导致serviceImpl文件生成失败");
        }else {
            List<String> serviceImplList = getStrings(entityName, commonPackage,  serviceImplPath);
            pk.setServiceImplName(this.getFileNameBylist(serviceImplList));
            pk.setServiceImplPackage(this.getPackageByList(serviceImplList));
            pk.setServiceImplSuperClassNme(this.getFileNameBySuperPath(info.getServiceImplSuperClassName()));
            pk.setServiceImplSuperClassPackage(this.getPackageBySuperPath(info.getServiceImplSuperClassName()));
        }

        //controller
        String ControllerPath = info.getControllerPackagePath();
        if(StringUtils.isBlank(ControllerPath)){
            log.error("没有设置controller文件的 controllerPackagePath会导致 会导致controller文件生成失败");
        }else{
            List<String> controllerList = getStrings(entityName, commonPackage, ControllerPath);
            pk.setControllerName(this.getFileNameBylist(controllerList));
            pk.setControllerPackage(this.getPackageByList(controllerList));
            pk.setControllerSuperClassNme(this.getFileNameBySuperPath(info.getControllerSuperClassName()));
            pk.setControllerSuperClassPackage(this.getPackageBySuperPath(info.getControllerSuperClassName()));
        }


        List<String> bcl = new ArrayList<>();
        StringBuffer row = new StringBuffer();
        for (int i = 0; i < table.getFields().size(); i++) {
            TableFieldProperties name = table.getFields().get(i);
            row.append(name.getFieldName());
            if(i != table.getFields().size()-1){
                row.append(", ");
            }
            if(row.length()>100||i == table.getFields().size()-1){
                bcl.add(row.toString());
                row = new StringBuffer();
            }

        }
        table.setBaseColumnList(bcl);

        //mapper
        String mapperPath = info.getMapperPackagePath();
        if(StringUtils.isBlank(mapperPath)){
            log.error("没有设置mapper文件的 mapperPackagePath 会导致mapper文件生成失败");
        }else {
            List<String> mapperList = getStrings(entityName, commonPackage, mapperPath);
            pk.setMapperName(this.getFileNameBylist(mapperList));
            pk.setMapperPackage(this.getPackageByList(mapperList));
            pk.setMapperSuperClassNme(this.getFileNameBySuperPath(info.getMapperSuperClassName()));
            pk.setMapperSuperClassPackage(this.getPackageBySuperPath(info.getMapperSuperClassName()));
        }

        //feign
        String feignPath = info.getFeignPackagePath();
        if(StringUtils.isBlank(feignPath)){
            log.error("没有设置feign文件的 feignPackagePath 会导致feignPath文件生成失败");
        }else{
            List<String> feignList = getStrings(entityName, commonPackage, feignPath);
            pk.setFeignName(this.getFileNameBylist(feignList));
            pk.setFeignPackage(this.getPackageByList(feignList));
            pk.setFeignSuperClassNme(this.getFileNameBySuperPath(info.getFeignSuperClassName()));
            pk.setFeignSuperClassPackage(this.getPackageBySuperPath(info.getFeignSuperClassName()));
        }

        //feignFallback
        String feignFallbackPath = info.getFeignFallbackPackagePath();
        if(StringUtils.isBlank(feignFallbackPath)){
            log.error("没有设置feignFallback文件的 feignFallbackPackagePath 会导致feignFallback文件生成失败");
        }else{
            List<String> feignFallbackList = getStrings(entityName, commonPackage, feignFallbackPath);
            pk.setFeignFallbackName(this.getFileNameBylist(feignFallbackList));
            pk.setFeignFallbackPackage(this.getPackageByList(feignFallbackList));
            pk.setFeignFallbackSuperClassNme(this.getFileNameBySuperPath(info.getFeignFallbackSuperClassName()));
            pk.setFeignFallbackSuperClassPackage(this.getPackageBySuperPath(info.getFeignFallbackSuperClassName()));
        }

        param.setPk(pk);



        for(TableFieldProperties field:table.getFields()) {
            String comment = field.getComments();
            if (CommonUtil.isNotEmpty(comment)) {
                int first = comment.indexOf("[");
                int end = comment.indexOf("]");
                if (first > -1 && end > -1 && end - first > 3) {
                    List<NotesProperties> notes = new ArrayList<>();
                    String str = comment.substring(first + 1, end);
                    String[] one = str.split(",");

                    for (String two : one) {
                        String[] three = two.split(":");
                        if (three.length != 2) {
                            throw new CustomizeRuntimeException("错误的格式,格式支持 [字段值:值描述,字段值:值描述....]");
                        }
                        NotesProperties note = new NotesProperties();
                        note.setKey(three[0]);
                        note.setDesc( three[1]);
                        note.setPinyin(CommonUtil.getPinYin(three[1]));
                        notes.add(note);
                    }
                    field.setNotes(notes);
                }
            }
        }
    }

    private String getPackageBySuperPath(String path){
        if(StringUtils.isBlank(path) ){
            return null;
        }
        return getPackageByList(Arrays.asList(path.split("\\.")));
    }

    private String getPackageByList(List<String> list){
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < list.size()-1; i++) {
            if(sb.length() != 0){
                sb.append(".");
            }
            sb.append(list.get(i));
        }
        return sb.toString();
    }
    private String getFileNameBySuperPath(String path){
        if(StringUtils.isBlank(path)){
            return null;
        }
        return getFileNameBylist(Arrays.asList(path.split("\\.")));
    }
    private String getFileNameBylist(List<String> list){
        return list.get(list.size()-1);
    }
    private TableProperties getTableProperties(){
        if(dataSourceProperties.getDriverClassName().contains("oracle")){
            return jdbcDao.queryOracleTableInfo(generateProperties.getInfo().getEntityTableName());
        }else if(dataSourceProperties.getDriverClassName().contains("mysql")) {
            return jdbcDao.queryMysqlTableInfo(generateProperties.getInfo().getEntityTableName());
        }else {
            throw new RuntimeException("未知的数据库类型");
        }
    }

    private List<TableFieldProperties> getTableFieldProperties(){
        if(dataSourceProperties.getDriverClassName().contains("oracle")){
            return jdbcDao.queryOracleTableFiledProperties(generateProperties.getInfo().getEntityTableName(),param);
        }else if(dataSourceProperties.getDriverClassName().contains("mysql")) {
            return jdbcDao.queryMysqlTableFiledProperties(generateProperties.getInfo().getEntityTableName(),param);
        }else {
            throw new RuntimeException("未知的数据库类型");
        }
    }

    private List<String> getPrimaryKeys(){
        if(dataSourceProperties.getDriverClassName().contains("oracle")){
            return jdbcDao.queryOraclePrimaryKeyFileds(generateProperties.getInfo().getEntityTableName());
        }else if(dataSourceProperties.getDriverClassName().contains("mysql")) {
            return jdbcDao.queryMysqlPrimaryKeyFileds(generateProperties.getInfo().getEntityTableName());
        }else {
            throw new RuntimeException("未知的数据库类型");
        }
    }


    private List<String> getStrings(java.lang.String entityName, java.lang.String commonPackage, java.lang.String filePath) {
        filePath = filePath.replaceAll("&entity&",entityName)
                .replaceAll(".java", "");
        java.lang.String filePackage =
                (commonPackage.trim()!=""?(commonPackage+"/"):"")+ filePath;
        filePackage = filePackage.replaceAll("/","\\.");
        return Arrays.asList(filePackage.split("\\."));
    }
    /**
     * @example bd_item_info--->BdItemInfo
     * @param
     * @return String
     *
     */
    private String dbForDBToHump(String str){
        StringBuffer sb = new StringBuffer();
        String[] fields = str.split("_");
        String temp = null;
        for ( int i = 0 ; i < fields.length ; i++ ) {
            temp = fields[i].trim();
            sb.append(temp.substring(0, 1).toUpperCase()).append(temp.substring(1));
        }
        return sb.toString();
    }
}
